<template>
  <div class="blood-sugar-container">
    <a-card title="血糖记录管理" :bordered="false">
      <template #extra>
        <a-space>
          <a-range-picker
            v-model:value="dateRange"
            :placeholder="['开始日期', '结束日期']"
            format="YYYY-MM-DD"
            @change="onDateChange"
          />
          <a-input-search
            v-model:value="searchKeyword"
            placeholder="用户名/手机号"
            style="width: 200px"
            @search="onSearch"
          />
          <a-button type="primary" @click="onSearch">
            <search-outlined />查询
          </a-button>
          <a-button @click="resetSearch">
            <reload-outlined />重置
          </a-button>
        </a-space>
      </template>
      
      <a-table
        :dataSource="bloodSugarList"
        :columns="columns"
        :loading="loading"
        rowKey="id"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <!-- 用户信息 -->
          <template v-if="column.key === 'user'">
            <div class="user-info">
              <span class="user-name">{{ record.userName || '未知用户' }}</span>
              <span class="user-phone">{{ record.userId ? 'ID: ' + record.userId : '-' }}</span>
            </div>
          </template>
          
          <!-- 血糖值 -->
          <template v-if="column.key === 'value'">
            <a-tag :color="getStatusColor(record.statusText)">
              {{ record.value }} mmol/L
              <span v-if="record.statusText" style="margin-left: 4px">({{ record.statusText }})</span>
            </a-tag>
          </template>
          
          <!-- 测量类型 -->
          <template v-if="column.key === 'type'">
            <a-tag :color="getTypeColor(record.measureType)">
              {{ record.measureTypeText || getTypeName(record.measureType) }}
            </a-tag>
          </template>
          
          <!-- 测量时间 -->
          <template v-if="column.key === 'measureTime'">
            {{ formatDateTime(record.measureTime) }}
          </template>
          
          <!-- 操作 -->
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="viewDetail(record)">查看</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除此记录吗？"
                @confirm="deleteRecord(record.id)"
                okText="确定"
                cancelText="取消"
              >
                <a class="delete-link">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { message } from 'ant-design-vue';
import {
  SearchOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue';
import dayjs from 'dayjs';

const router = useRouter();

// 数据状态
const bloodSugarList = ref([]);
const loading = ref(false);
const searchKeyword = ref('');
const dateRange = ref([]);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total) => `共 ${total} 条记录`
});

// 日期变化处理
const onDateChange = (dates) => {
  dateRange.value = dates || [];
};

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '用户',
    key: 'user',
    width: 150
  },
  {
    title: '血糖值',
    key: 'value',
    dataIndex: 'value',
    width: 120,
    sorter: true
  },
  {
    title: '类型',
    key: 'type',
    dataIndex: 'measureType',
    width: 120,
    filters: [
      { text: '空腹', value: 1 },
      { text: '餐后', value: 2 },
      { text: '随机', value: 3 }
    ]
  },
  {
    title: '测量时间',
    key: 'measureTime',
    dataIndex: 'measureTime',
    width: 180,
    sorter: true
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'note',
    ellipsis: true
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right'
  }
];

// 获取血糖记录列表
const fetchBloodSugarList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {
      page: pagination.value.current,
      pageSize: pagination.value.pageSize,
      keyword: searchKeyword.value
    };
    
    // 添加日期范围参数
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dayjs(dateRange.value[0]).format('YYYY-MM-DD');
      params.endDate = dayjs(dateRange.value[1]).format('YYYY-MM-DD');
    }
    
    const response = await axios.get('/admin/blood-sugar/list', { params });
    
    if (response.data.code === 0) {
      bloodSugarList.value = response.data.data.records || [];
      pagination.value.total = response.data.data.total || 0;
    } else {
      message.error(response.data.message || '获取血糖记录失败');
    }
  } catch (error) {
    message.error('获取血糖记录失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 监听搜索条件变化
watch(
  [() => pagination.value.current, () => pagination.value.pageSize],
  () => {
    fetchBloodSugarList();
  }
);

// 表格变化处理
const handleTableChange = (pag, filters, sorter) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
};

// 搜索
const onSearch = () => {
  pagination.value.current = 1;
  fetchBloodSugarList();
};

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = '';
  dateRange.value = null;
  pagination.value.current = 1;
  fetchBloodSugarList();
};

// 查看详情
const viewDetail = (record) => {
  router.push(`/blood-sugar/${record.id}`);
};

// 删除记录
const deleteRecord = async (id) => {
  try {
    const response = await axios.delete(`/admin/blood-sugar/${id}`);
    
    if (response.data.code === 0) {
      message.success('删除成功');
      fetchBloodSugarList();
    } else {
      message.error(response.data.message || '删除失败');
    }
  } catch (error) {
    message.error('删除失败: ' + error.message);
  }
};

// 格式化日期时间
const formatDateTime = (dateTimeArr) => {
  if (!dateTimeArr || !Array.isArray(dateTimeArr) || dateTimeArr.length < 5) return '-';
  
  // 日期数组格式: [年, 月, 日, 时, 分]
  const [year, month, day, hour, minute] = dateTimeArr;
  const formattedMonth = String(month).padStart(2, '0');
  const formattedDay = String(day).padStart(2, '0');
  const formattedHour = String(hour).padStart(2, '0');
  const formattedMinute = String(minute).padStart(2, '0');
  
  return `${year}-${formattedMonth}-${formattedDay} ${formattedHour}:${formattedMinute}`;
};

// 获取血糖值颜色
const getBloodSugarColor = (value) => {
  if (value < 3.9) return 'red';
  if (value > 7.8) return 'orange';
  return 'green';
};

// 获取类型名称
const getTypeName = (type) => {
  const typeMap = {
    1: '空腹',
    2: '餐后',
    3: '随机'
  };
  return typeMap[type] || '未知';
};

// 获取类型颜色
const getTypeColor = (type) => {
  const colorMap = {
    1: 'blue',
    2: 'green',
    3: 'purple'
  };
  return colorMap[type] || 'default';
};

// 获取状态颜色
const getStatusColor = (statusText) => {
  if (!statusText) return 'green';
  if (statusText.includes('偏低')) return 'red';
  if (statusText.includes('偏高')) return 'orange';
  return 'green';
};

// 组件挂载时获取数据
onMounted(() => {
  fetchBloodSugarList();
});
</script>

<style scoped>
.blood-sugar-container {
  padding: 24px;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 500;
}

.user-phone {
  font-size: 12px;
  color: #999;
}

.delete-link {
  color: #ff4d4f;
}
</style> 